<?php namespace App\Http\Middleware;

use App\Http\Classes\Common;
use App\Http\Classes\User;
use Closure;

class AccessToken {

	/**
	 * Handle an incoming request.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Closure  $next
	 * @return mixed
	 */
	public function handle($request, Closure $next)
	{
        if(isset($_COOKIE['user_token']) && isset($_COOKIE['user_id'])){
            $id = $_COOKIE['user_id'];
            $token = $_COOKIE['user_token'];
            if(User::accessTokenVerifly($id,$token)){
                return $next($request);
            }
            else{
                setcookie("user_token", "", time()-3600,'/');
                setcookie('user_id','',time()-3600,'/');
                //return redirect("login.html");
                return Common::response(503,'你的通行证已经过期了',null);
            }
        }
        else if($request->has('user_token') && $request->has('user_id')){
            $id = $request->input('user_id');
            $token = $request->input('user_token');
            if(User::accessTokenVerifly($id,$token)){
                return $next($request);
            }
            else{
                setcookie("user_token", "", time()-3600,'/');
                setcookie('user_id','',time()-3600,'/');
                //return redirect("login.html");
                return Common::response(503,'你的通行证已经过期了',null);
            }
        }
        else{
            setcookie("user_token", "", time()-3600,'/');
            setcookie('user_id','',time()-3600,'/');
            //return redirect("login.html");
            return Common::response(503,'你没有这个世界的通行证',null);
        }
	}
}
